package com.zq.zhufengfm.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.MediaStore;

import com.zq.zhufengfm.Constants;
import com.zq.zhufengfm.entity.Tracks;

import java.io.IOException;
import java.util.ArrayList;

/**
 * Project_name : ZhuFengFM
 * Author : zhaoQiang
 * Date : 2015/10/25,20:46
 * Email : zhaoq_hero@163.com
 */
public class TrackPlayerService extends Service{

    private ArrayList<Tracks> tracksArrayList; //播放的所有音乐文件

    private MediaPlayer mediaPlayer;//媒体文件的播放组件


    @Override
    public void onCreate() {
        //TODO 初始化service组件
        super.onCreate();

        //实例化  MediaPlayer
        mediaPlayer = new MediaPlayer();
    }

    //实际上就是接收参数  intent  对intent进行操作：
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        //获取集合
        tracksArrayList = intent.getParcelableArrayListExtra(Constants.SERVICE_PLAY_LIST);
        //获取位置
        int position = intent.getIntExtra(Constants.CLICK_TRACKS_POSITION,0);
        //获取  地址
        String url = tracksArrayList.get(position).getPlayPathAacv164();

        //重置  播放音乐的组件
        mediaPlayer.reset();

        try {
            mediaPlayer.setDataSource(url);//设置播放资源

            mediaPlayer.prepareAsync();//异步任务请求数据

            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                //设置播放的  方法：
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

        return super.onStartCommand(intent, flags, startId);

    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        mediaPlayer.release();
        super.onDestroy();
    }
}
